/**
 * 前台教师PC端
 *        外出申请子模块JS代码
 */
function JsonOBJ() {
    this.id = null;
    this.majorname = null;
    this.classname = null;
    this.studentname = null;
    this.startTime = null;
    this.endTime = null;
    this.teachername = null;
    this.requestReason = null;
    this.rejectReason = null;
    this.authStatus = null;
    this.requestTime = null;
}

var pageNo = 1;     //当前页
var pageSize = 3;   //每页记录数
var pageCount = 1;
var tabCurrent = 0; //当前标签，待审批，代发，历史记录
var islogin = 1;
var isSubmit = 0;
var dataJson;  //查询参数
$(function () {
    /*--------------------------------------------------------------------*/
    $(".exit-btn").click(function () {
        $.ajax({
            url: "/door/front/teacher/exit?" + new Date().getTime(),
            async: false,
            success: function () {
                window.location.href = "/door/front_end/pc/teacher/login_pc_teacher.html";
            }
        });
    });
    if ($("title").text() == "审批历史") {
        $(".search-btn").click(function () {
            pageNo = 1;
            queryData();
            return false;
        });
        $("select").change(function () {
            pageNo = 1;
            $("#type").attr("value",$("select").val());
            queryData();
        });
        laydate({
            elem: '#date-start',
            format: 'YYYY-MM-DD hh:mm:ss',
            istime: false,
            isclear: false, //是否显示清空
            istoday: false, //是否显示今天
            festival: true, //显示节日
            choose: function (datas) { //选择日期完毕的回调
                pageNo = 1;
                queryData();
            }
        });
        laydate({
            elem: '#date-end',
            format: 'YYYY-MM-DD hh:mm:ss',
            istime: false,
            isclear: false, //是否显示清空
            istoday: false, //是否显示今天
            festival: true, //显示节日
            choose: function (datas) { //选择日期完毕的回调
                pageNo = 1;
                queryData();
            }
        });
        queryData();
    }
    if ($("title").text() == "待审批申请") {
        $("#sureBtn").click(function () {
            approveList(0);
        });
        $("#notSureBtn").click(function () {
            var i = 0;
            $("img[id]").each(function () {
                if ($(this).attr("check_type") == 1)
                    i++;
            });
            if (i == 0) {
                layer.msg("至少勾选一条数据", {time: 1000});
            } else {
                $("#notSureModal").modal('show');
            }
        });
        $("#rejectBtn").click(function () {
            approveList(1);
            return false;
        });
        queryData();
    }

    if ($("title").text() == "代发申请") {
        pageSize = 20;
        laydate({
            elem: '#date-start',
            format: 'YYYY-MM-DD hh:mm:ss',
            istime: true,
            isclear: false, //是否显示清空
            istoday: false, //是否显示今天
            festival: true, //显示节日
            choose: function (datas) { //选择日期完毕的回调
                
            }
        });
        laydate({
            elem: '#date-end',
            format: 'YYYY-MM-DD hh:mm:ss',
            istime: true,
            isclear: false, //是否显示清空
            istoday: false, //是否显示今天
            festival: true, //显示节日
            choose: function (datas) { //选择日期完毕的回调

            }
        });
        $("#replaceBtn").click(function () {
            var i = 0;
            $("img[id]").each(function () {
                if ($(this).attr("check_type") == 1)
                    i++;
            });
            if (i == 0) {
                layer.msg("至少勾选一个学生", {time: 1000});
            } else {
                $("#replaceModal").modal('show');
            }
        });
        $("#sureReplace").click(function () {
            replaceList();
            return false;
        });
        queryData();
    }
    init();
});

function init() {
    $.ajax({
        url: "/door/front/teacher/getCurTea?" + new Date().getTime(),
        async: false,
        success: function (str) {
            if (check(str)) {
                $("#teacher_name").text(str.teachername);
                $("#teacher_class").text(str.name);
            }
        }
    });
}

/**
 * 检查用户是否登录
 *    如果未登录，返回教师端登录页面
 * @param str
 * @returns {Boolean}
 */
function check(str) {
    if (str != null && str != "" || str == 0) {
        if (str.errorcode != undefined) {
            if (str.errorcode == 1) {
                if (islogin == 1) {
                    layer.msg(str.errormessage, {time: 1000});
                    window.location.href = "/door/front_end/pc/teacher/login_pc_teacher.html";
                    islogin = 0;
                }
            }
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function setDataOfList(records) {
    $(".right-detail .apply-item").remove();
    var str = '';

    for (var i = 0; i < records.length; i++) {
        var status_str = null;
        var status_class = null;
        switch (records[i].authStatus) {
            case 0 :
                status_str = "审批中";
                status_class = "state-ing";
                break;
            case 1 :
                status_str = "审批通过";
                status_class = "state-yes";
                break;
            case 2 :
                status_str = "审批驳回";
                status_class = "state-no";
                break;
            case 3 :
                status_str = "撤销";
                status_class = "state-cancel";
                break;
        }
        str += '<div class="apply-item text-center"><div><div class="checkBox fl">' +
            '<img src="../../../images/img_xuanzhe_01.png" alt="" class="check" check_type=0 id=' +
            records[i].id + '></div><p>' +
            records[i].classname + '</p><p>' +
            records[i].studentname + '</p></div><div><label>请假时长：</label><p>' +
            DateUtils.format(new Date(records[i].startTime), "yyyy-MM-dd HH:mm:ss") + '</p><p>至</p><p>' +
            DateUtils.format(new Date(records[i].endTime), "yyyy-MM-dd HH:mm:ss") + '</p><p class="' +
            status_class + '">' +
            status_str + '</p></div><div><label>请假原因：</label><div class="reason">' +
            records[i].requestReason + '</div><a href="#" onclick="hisOnclick('+records[i].id+')"><p class="to-detail">查看详情>> </p></a></div></div>';
    }
    // $("#pageCount").text(pager.pageCount);
    $(".pagination-table").before(str);
}
function hisOnclick(id){
	sessionStorage.setItem("id", id);
	window.location.href="/door/front_end/pc/teacher/apply.detailsPC_teacher.html";//跳转到详情页...
	
	
	//在xxxx.html: 获取id;根据id获取详情(ajax)
}
function setDataOfStuList(students) {
    $("#students_ul").empty();
    var str = '';

    for (var i = 0; i < students.length; i++) {
        str += '<li class="col-sm-3 student-name"><ul class="student-area"><li class="fl checkBox margin-cancel">' +
            '<img src="../../../images/img_xuanzhe_01.png" alt="" class="check" check_type=0 id=' +
            students[i].code + '></li><li><h4 class="name-border">' +
            students[i].name + '<br/>' +
            students[i].code + '</h4></li></ul></li>'
    }

    $("#students_ul").html(str);
}

function queryData() {
    tabCurrent = $("#type").attr("value");
    var sdate = $("#date-start").val();
    var edate = $("#date-end").val();
    var stuName = $(".seek-box").val();

    if (typeof(sdate) == "undefined" || sdate == "") {
        sdate = "1970-01-01 00:00:00";
    }
    if (typeof(edate) == "undefined" || edate == "") {
        edate = "2160-01-01 00:00:00";
    }
    if (typeof(stuName) == "undefined") {
        stuName = "";
    }
    dataJson = {
        startDate: sdate,
        endDate: edate,
        stuName: stuName,
        pageNo: pageNo,
        pageSize: pageSize,
        type: tabCurrent
    };
    if ($("title").text() == "代发申请") {
        queryDataOfStu();
    } else {
        getDataOfRecord();
    }
}

function queryDataOfStu() {
    $.ajax({
        async: true,
        type: 'POST',
        url: '/door/front/teacher/getCurTeaStus',
        data: {
            pageSize: 24,
            pageNo: pageNo
        },
        cache: false,
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        beforeSend: function (xhr) {
        },
        success: function (data, textStatus, xhr) {
            if (check(data)) {
                if (data.itemCount == 0) {
                    layer.msg("没有数据", {time: 1000});
                }
                pageCount = Math.floor((data.itemCount + pageSize - 1) / pageSize);
                setTableBTN();
                setDataOfStuList(data.list);
                toggleChecked();
            }
        },
        error: function (xhr, textStatus, errorInfo) {
        },
        complete: function (xhr, textStatus) {
        }
    });
}

function getDataOfRecord() {//带参分页查询函数
    $.ajax({
        async: true,
        type: 'POST',
        url: '/door/front/teacher/apply',
        data: dataJson,
        cache: false,
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        beforeSend: function (xhr) {
        },
        success: function (data, textStatus, xhr) {
            if (check(data)) {
                if (data.itemCount == 0) {
                    layer.msg("没有数据", {time: 1000});
                }
                pageCount = Math.floor((data.itemCount + pageSize - 1) / pageSize);
                setTableBTN();
                setDataOfList(data.list);
                toggleChecked();
            }
        },
        error: function (xhr, textStatus, errorInfo) {
        },
        complete: function (xhr, textStatus) {
        }
    });
}

function setTableBTN() {
    var pagination_li = $(".pager li");
    var pagination_a = $(".pager a");

    if(pageNo==1){
        pagination_a.eq(6).html(pageNo + 4);
        pagination_a.eq(5).html(pageNo + 3);
        pagination_a.eq(4).html(pageNo + 2);
        pagination_a.eq(3).html(pageNo + 1);
        pagination_a.eq(2).html(pageNo);
        pagination_li.each(function (i) {
            $(this).removeClass("active");
            if (pageNo == parseInt($(this).text())) {
                $(this).addClass("active");
            }
        });
    }

    pagination_li.each(function (i) {
        if (i == 1) {//上一页按钮
            this.onclick = function () {
                if (pageNo > 1) {
                    pageNo--;

                    if (pageNo < parseInt(pagination_a.eq(2).html())) {
                        pagination_a.eq(6).html(pageNo + 4);
                        pagination_a.eq(5).html(pageNo + 3);
                        pagination_a.eq(4).html(pageNo + 2);
                        pagination_a.eq(3).html(pageNo + 1);
                        pagination_a.eq(2).html(pageNo);
                    }
                    pagination_li.each(function (i) {
                        $(this).removeClass("active");
                        if (pageNo == parseInt($(this).text())) {
                            $(this).addClass("active");
                        }
                    });
                    queryData();
                } else {
                    layer.msg("当前是第一页", {time: 1000});
                }
            };
        } else if (i == 7) {//下一页按钮
            this.onclick = function () {
                if (pageNo < pageCount) {
                    pageNo++;

                    if (pageNo > parseInt(pagination_a.eq(6).html())) {
                        pagination_a.eq(6).html(pageNo);
                        pagination_a.eq(5).html(pageNo - 1);
                        pagination_a.eq(4).html(pageNo - 2);
                        pagination_a.eq(3).html(pageNo - 3);
                        pagination_a.eq(2).html(pageNo - 4);
                    }
                    pagination_li.each(function (i) {
                        $(this).removeClass("active");
                        if (pageNo == parseInt($(this).text())) {
                            $(this).addClass("active");
                        }
                    });
                    queryData();
                } else {
                    layer.msg("当前是最后一页", {time: 1000});
                }
            };
        } else if (i == 0) {
            this.onclick = function () {
                pageNo = 1;

                if (pageNo < parseInt(pagination_a.eq(2).html())) {
                    pagination_a.eq(6).html(pageNo + 4);
                    pagination_a.eq(5).html(pageNo + 3);
                    pagination_a.eq(4).html(pageNo + 2);
                    pagination_a.eq(3).html(pageNo + 1);
                    pagination_a.eq(2).html(pageNo);
                }
                pagination_li.each(function (i) {
                    $(this).removeClass("active");
                    if (pageNo == parseInt($(this).text())) {
                        $(this).addClass("active");
                    }
                });
                queryData();
            };
        } else if (i == 8) {
            this.onclick = function () {
                pageNo = pageCount;

                if (pageNo > parseInt(pagination_a.eq(6).html())) {
                    pagination_a.eq(6).html(pageNo);
                    pagination_a.eq(5).html(pageNo - 1);
                    pagination_a.eq(4).html(pageNo - 2);
                    pagination_a.eq(3).html(pageNo - 3);
                    pagination_a.eq(2).html(pageNo - 4);
                }
                pagination_li.each(function (i) {
                    $(this).removeClass("active");
                    if (pageNo == parseInt($(this).text())) {
                        $(this).addClass("active");
                    }
                });
                queryData();
            };
        } else {//普通翻页按钮
            this.onclick = function () {
                var index = parseInt(this.innerText);
                if (index > pageCount) {
                    index = pageCount;
                    layer.msg("共" + pageCount + "页", {time: 1000});
                }
                pageNo = index;
                pagination_li.each(function (i) {
                    $(this).removeClass("active");
                    if (pageNo == parseInt($(this).text())) {
                        $(this).addClass("active");
                    }
                });
                queryData();
            }
        }
    });
}

function toggleChecked() {
    $(".checkBox img").each(function () {
        $(this).click(function () {
            if ($(this).attr("check_type") == 0) {
                $(this).attr("check_type", 1);
                $(this).attr("src", "../../../images/img_xuanzhe_02.png")
            } else {
                $(this).attr("check_type", 0);
                $(this).attr("src", "../../../images/img_xuanzhe_01.png")
            }
        })
    });
    $(".allCheck img").click(function () {
        if ($(this).attr("check_type") == 0) {
            $(this).attr("check_type", 1);
            $(this).attr("src", "../../../images/img_xuanzhe_02.png");
            $(".checkBox img").each(function () {
                $(this).attr("check_type", 1);
                $(this).attr("src", "../../../images/img_xuanzhe_02.png")
            });
        } else {
            $(this).attr("check_type", 0);
            $(this).attr("src", "../../../images/img_xuanzhe_01.png");
            $(".checkBox img").each(function () {
                $(this).attr("check_type", 0);
                $(this).attr("src", "../../../images/img_xuanzhe_01.png");
            });
        }
    });
}

function replaceList() {
    if (checkInput() == 0) {
        var checkIds = new Array();
        $("img[id]").each(function () {
            if ($(this).attr("check_type") == 1) {
                var js = new JsonOBJ();
                js.studentname = $(this).attr("id");
                js.requestReason = $("#causeBack").val();
                js.startTime = new Date($("#date-start").val());
                js.endTime = new Date($("#date-end").val());
                checkIds.push(js);
            }
        });
        $("#replaceModal").modal('hide');
        $.ajax({
            url: "/door/front/teacher/replace?" + new Date().getTime(),
            type: "post",
            data: JSON.stringify(checkIds),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            async: false,
            success: function (str) {
                if (check(str)) {
                    if (checkIds.length != parseInt(str)) {
                        layer.msg("失败" + (checkIds.length - parseInt(str)) + "条", {time: 1500});
                    } else {
                        layer.msg("代发成功", {time: 1500});
                    }
                }
            }
        });
    }
}

function approveList(type) {
    var checkIds = new Array();
    $("img[id]").each(function () {
        if ($(this).attr("check_type") == 1) {
            var js = new JsonOBJ();
            js.id = $(this).attr("id");
            if (type == 0) {
                js.authStatus = 1;
                js.rejectReason = "";
            } else {
                js.authStatus = 2;
                js.rejectReason = $("#caused").val();
            }
            checkIds.push(js);
        }
    });
    if ($("#caused").val() == "" && type == 1) {
        layer.msg("拒绝理由不能为空", {time: 1000});
        return;
    }
    if (checkIds.length == 0) {
        layer.msg("至少勾选一条数据", {time: 1000});
    } else {
        $.ajax({
            url: "/door/front/teacher/approve?" + new Date().getTime(),
            type: "post",
            data: JSON.stringify(checkIds),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            async: false,
            success: function (str) {
                if (check(str)) {
                    $("#notSureModal").modal('hide');
                    if (type == 0) {
                        if (str == checkIds.length) {
                            $('#myModalLabel').text('批准成功');
                            $("#modal-body").text('已批准成功！');
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        } else {
                            $('#myModalLabel').text('批准失败');
                            $("#modal-body").text("失败" + (checkIds.length - parseInt(str)) + "条！");
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        }
                    } else {
                        if (str == checkIds.length) {
                            $('#myModalLabel').text('不批准');
                            $("#modal-body").text('提交成功！');
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        } else {
                            $('#myModalLabel').text('不批准');
                            $("#modal-body").text("失败" + (checkIds.length - parseInt(str)) + "条！");
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        }
                    }
                }
            }
        });
    }
}

function checkInput() {
    var st = $("#date-start").val();
    var et = $("#date-end").val();
    var reason = $("#causeBack").val();
    if (st != "" && et != "") {

        if (reason != "") {
            var sTime = new Date(st);
            var eTime = new Date(et);
            var nTime = new Date();
            if (sTime <= nTime) {
                layer.msg("起始日期不能早于当前时间", {time: 1000});
                return 3;
            } else if (sTime >= eTime) {
                layer.msg("结束日期不能早于起始日期", {time: 1000});
                return 4;
            } else {
                return 0;
            }
        } else {
            layer.msg("请假原因不能为空", {time: 1000});
            return 2;
        }
    } else {

        layer.msg("日期不能为空", {time: 1000});
        return 1;
    }
}